<template>
  <div class="demo-container">
    <el-button type="primary" @click="openDialog">打开表单对话框</el-button>

    <el-dialog
      v-model="dialogVisible"
      title="动态表单示例"
      width="70%"
      @closed="handleDialogClosed"
    >
      <DynamicForm
        ref="dynamicFormRef"
        :form-config="formConfig"
        v-model="formData"
        @submit-success="handleFormSubmitSuccess"
        @submit-fail="handleFormSubmitFail"
        :submit-loading="submitLoading"
        label-width="120px"
      />

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleDialogSubmit">
          确认提交
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  // import type { FormItemConfig } from '@/components/DynamicForm/type'

  interface FormData {
    username: string
    age: number
    gender: 'male' | 'female'
    hobbies: string[]
    birthday: string
    agree: boolean
  }

  const dialogVisible = ref(false)
  const submitLoading = ref(false)
  const dynamicFormRef = ref<FormInstance>()

  const formData = reactive<FormData>({
    username: '',
    age: 0,
    gender: 'male',
    hobbies: [],
    birthday: '',
    agree: false
  })

  const formConfig = [
    {
      type: 'input',
      label: '用户名',
      prop: 'username',
      span: 12,
      attrs: {
        maxlength: 20
      },
      rules: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
    },
    {
      type: 'input',
      label: '年龄',
      prop: 'age',
      span: 12,
      attrs: {
        type: 'number',
        min: 0,
        max: 150
      },
      rules: [
        {
          type: 'number',
          required: true,
          message: '请输入有效年龄',
          trigger: 'blur'
        }
      ]
    },
    {
      type: 'radio-group',
      label: '性别',
      prop: 'gender',
      span: 12,
      children: [
        { type: 'radio', label: '男', value: 'male' },
        { type: 'radio', label: '女', value: 'female' }
      ],
      rules: [{ required: true, message: '请选择性别', trigger: 'change' }]
    },
    {
      type: 'checkbox-group',
      label: '兴趣爱好',
      prop: 'hobbies',
      span: 24,
      children: [
        { type: 'checkbox', label: '阅读', value: 'read' },
        { type: 'checkbox', label: '运动', value: 'sport' },
        { type: 'checkbox', label: '音乐', value: 'music' },
        { type: 'checkbox', label: '旅行', value: 'travel' }
      ],
      rules: [
        {
          required: true,
          message: '至少选择一个兴趣爱好',
          trigger: 'change'
        }
      ]
    },
    {
      type: 'date',
      label: '出生日期',
      prop: 'birthday',
      span: 12,
      attrs: {
        type: 'date',
        'value-format': 'YYYY-MM-DD',
        placeholder: '选择日期'
      },
      rules: [
        {
          required: true,
          message: '请选择出生日期',
          trigger: 'change'
        }
      ]
    },
    {
      type: 'switch',
      label: '同意协议',
      prop: 'agree',
      span: 24,
      attrs: {
        'active-text': '同意',
        'inactive-text': '不同意'
      },
      rules: [
        {
          validator: (_rule: any, value: boolean, callback: (error?: string | Error) => void) => {
            if (value) {
              callback()
            } else {
              callback('必须同意协议')
            }
          },
          trigger: 'change'
        }
      ]
    }
  ]

  const openDialog = () => {
    dialogVisible.value = true
  }

  const handleDialogClosed = () => {
    // 重置表单数据和验证状态
    // Object.assign(formData, {
    //   username: '',
    //   age: 0,
    //   gender: 'male',
    //   hobbies: [],
    //   birthday: '',
    //   agree: false
    // })
    // dynamicFormRef.value?.resetFields()
  }

  const handleDialogSubmit = async () => {
    try {
      submitLoading.value = true
      await dynamicFormRef.value?.handleSubmit()
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  const handleFormSubmitSuccess = async (data: FormData) => {
    try {
      // 模拟API调用
      console.log('提交数据:', data)
      // await api.submitForm(data)

      ElMessage.success('提交成功')
      dialogVisible.value = false
    } catch (error) {
      ElMessage.error('提交失败')
    }
  }

  const handleFormSubmitFail = (error: any) => {
    console.error('验证失败:', error)
    ElMessage.error('表单验证失败，请检查输入')
  }
</script>

<style scoped>
  .demo-container {
    padding: 20px;
  }
</style>
